package org.budo.sharding.hint;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.budo.sharding.hint.annotation.MasterOnly;
import org.budo.sharding.hint.annotation.RoutingDataSource;
import org.budo.support.lang.util.ArrayUtil;
import org.springframework.core.annotation.AnnotationUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class AnnotationMasterOnlySupport {
    private Boolean defaultMasterOnly = false;

    // 默认值
    private Class<Annotation>[] annotations = new Class[] { MasterOnly.class };

    /**
     * 设置单个注解
     */
    public void setAnnotation(Class<Annotation> annotation) {
        this.annotations = ArrayUtil.toArray(annotation);
    }

    protected String annotatedRoutingDataSource(Method method) {
        if (null == method) {
            log.error("#36 method=" + method);
            return null;
        }

        RoutingDataSource annotation = AnnotationUtils.getAnnotation(method, RoutingDataSource.class);
        if (null == annotation) {
            return null;
        }

        return annotation.value();
    }

    /**
     * 方法上是否带有注解
     */
    protected boolean annotatedMasterOnly(Method method) {
        if (null == method || null == this.getAnnotations()) {
            log.error("#46 method=" + method + ", annotations=" + this.getAnnotations());
            return false;
        }

        for (Class<Annotation> annotationType : this.getAnnotations()) {
            Annotation annotation = AnnotationUtils.getAnnotation(method, annotationType);
            if (null != annotation) {
                if (annotation instanceof MasterOnly) { // 支持用 @MasterOnly(false) 指定 true false
                    return ((MasterOnly) annotation).value();
                }

                return true; // 其他的注解，有就是true，没有就是false
            }
        }

        return false;
    }
}